'use strict';

import Base from './base.js';

export default class extends Base {
  /**
   * index action
   * @return {Promise} []
   */
  indexAction(){
    //auto render template file index_index.html
    return this.display();
  }
  //注册接口
  async doregisterAction(){
    let newData=this.post();
        newData.password=think.md5(newData.password);

    // 后台校验
    newData.createtime=think.datetime(this.post('createtime'));

    if(newData.name !==''&& newData.password!==''&& newData.email!==''){
      //校验用户是否存在
      let s = await this.checkIsExist({name: newData.name})
      let userFlag = await this.checkIsExist({name: newData.name});
      let emailFlag = await this.checkIsExist({email: newData.email});

      if(userFlag===0){
        return this.fail(2);
      }else if(emailFlag===0){
        return this.fail(3);
      }else{
        let rs=await this.model('home').addOne('sys_user', newData);

        let userInfo={
            id:rs,
            name: newData.name,
            nickname: newData.nickname,
            email: newData.email,
            createtime: newData.createtime,
          }
        await this.session("userInfo", userInfo);
        if(rs) return this.success();
      }
    }else{
      return this.fail(4);
    }
  }

  //检查是否存在
  async checkIsExist(where){
      let rs= await this.model('home').findUser(where);
      let s=(rs.length>0)?0:1;
      return s;
  }

  //检查用户名是否存在
  async checknameAction(){
    let name=await this.post('name');
    let s=await this.checkIsExist({name:name});
    return s === 1? this.success(): this.fail(2);
  }

  //检查邮箱是否存在
  async checkemailAction(){
    let email=await this.post('email');
    let s=await this.checkIsExist({email:email});
    return s === 1? this.success(): this.fail(3);
  }
}